<template>
    <div class="stbh">
        <div id="mapDiv" class="mapDiv"></div>
        <div id="one" class="zoology" @click="dialog111">
        	<i class="iconfont iconfangxiang" style="font-size:20px;"></i>
            <div>基地</div>
        </div>
		<div class="zoology1">
			<div id="two" style="display:inline-block;width: 98px; text-align: center; border-right:1px solid #aaa;border-top-left-radius:6px ;border-bottom-left-radius:6px ;" @click="gotrack">
				<i class="iconfont iconguiji1" style="font-size:30px;"></i>
				<div>
					放养轨迹
				</div>
			</div>
		    <div id="three" style="display:inline-block;width:100px; text-align: center;border-top-right-radius:6px ;border-bottom-right-radius:6px ;" @click="farmarea">
				<i class="iconfont icondikuai" style="font-size:20px;"></i>
				<div>
					养殖区域
				</div> 
			</div>
		</div>
		<div class="zoology2">
		    <div id="four" style="display:inline-block;width: 100px; text-align: center; border-right:1px solid #aaa;;border-top-left-radius:6px ;border-bottom-left-radius:6px ;" @click="weather">
			   <i class="iconfont iconsheshidu" style="font-size:20px;"></i>
			   <div>
				   气象传感
			   </div>
			</div>
		    <div id="five" style="display:inline-block;width: 98px; text-align: center; border-right:1px solid #aaa;" @click="camera">
			   <i class="iconfont iconshexiangtou" style="font-size:20px;"></i>
			   <div>
				   摄像头
			   </div>
			</div>
		    <div id="six" style="display:inline-block;width: 99px; text-align: center;border-top-right-radius:6px ;border-bottom-right-radius:6px ;" @click="panoramagram">
			    <i class="iconfont iconquanjingtu" style="font-size:20px;"></i>
			    <div>
				   全景图
			    </div>
			</div>
		</div>
        <div class="address">
            <input v-model="addressname" style="border:none;border-right:1px solid #aaa;outline:none;" class="addressinput">
            <span class="addressspan" style="text-align: center;margin-left:4px;" @click="sousuo">搜索</span>
        </div>
        <el-drawer
            :before-close="handleClose"
            :visible.sync="dialog"
            direction="rtl"
            custom-class="drawer"
            ref="drawer"
            >
			<div class="demo-drawer__content" >
				
				<el-form :model="form" class="margin-left" label-width="80px" v-if="ruleForm.type == 1">
					<div class="hnk jgxx">基地信息</div>
					<el-form-item label="基地名称">
						<el-input v-model="ruleForm.name" autocomplete="off" style="width:150px;"></el-input>
					</el-form-item>
					<el-form-item label="面积">	
						<el-input v-model="ruleForm.area" autocomplete="off" style="width:150px;"></el-input>
						<span style="margin-left: 10px;">亩</span>
					</el-form-item>
					<el-form-item label="颜色">
						<div class="block">
							<el-color-picker v-model="ruleForm.color"></el-color-picker>
						</div>
					</el-form-item>
					<el-form-item label="透明度">
						<div class="block">
						    <span class="demonstration">默认</span>
						    <el-slider v-model="ruleForm.diaphaneity" style="width:120px;"></el-slider>
						  </div>
					</el-form-item>
				</el-form>
				<el-form :model="form" class="margin-left" label-width="80px" v-if="ruleForm.type == 2">
					<div class="hnk jgxx">地块信息</div>
					<el-form-item label="地块名称">
						<el-input v-model="ruleForm.name" autocomplete="off" style="width:150px;"></el-input>
					</el-form-item>
					<el-form-item label="面积">	
						<el-input v-model="ruleForm.area" autocomplete="off" style="width:150px;"></el-input>
						<span style="margin-left: 10px;">亩</span>
					</el-form-item>
					<el-form-item label="颜色">
						<div class="block">
							<el-color-picker v-model="ruleForm.color"></el-color-picker>
						</div>
					</el-form-item>
					<el-form-item label="透明度">
						<div class="block">
						    <span class="demonstration">默认</span>
						    <el-slider v-model="ruleForm.diaphaneity" style="width:120px;"></el-slider>
						  </div>
					</el-form-item>
					<div class="hnk jgxx">人员信息</div>
					<el-form-item label="农户：">
						<template>
							<el-select
					            v-model="peasantId"
								@change="choosePrincipal"
								value-key="id"
								style="width:300px"
								placeholder="请选择"
							>
								<el-option
									v-for="item in userList"
									:key="item.id"
									:label="item.name"
									:value="item"
								></el-option>
							</el-select>
						</template>
					</el-form-item>
					<el-form-item label="管理员：">
						<template>
							<el-select
					            v-model="principalId"
								@change="choosePrincipal1"
								value-key="id"
								style="width:300px"
								placeholder="请选择"
							>
								<el-option
									v-for="item in userList"
									:key="item.id"
									:label="item.name"
									:value="item"
								></el-option>
							</el-select>
						</template>
					</el-form-item>
				</el-form>
				<el-form :model="form" class="margin-left" label-width="100px" v-if="ruleForm.type == 5">
					<el-form-item label="名称">
						<el-input v-model="ruleForm.name" autocomplete="off" style="width:200px;"></el-input>
					</el-form-item>
					<el-form-item label="照片上传：">
					    <el-upload
					        class="upload-poster"
					        action="https://jsonplaceholder.typicode.com/posts/"
					        :show-file-list="false"
					        :on-change="imgPreview"
					        :auto-upload="false"
					    >
					        <img v-if="soilImg" :src="soilImg" class="avatar" />
					        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
					    </el-upload>jpg、png、gif格式，60x60像素，不超过2MB
					</el-form-item>
					<el-form-item label="拍摄时间：">
					    <el-date-picker
					        v-model="ruleForm.imgTime"
					        type="date"
					        value-format="yyyy-MM-dd"
					        placeholder="请选择"
					        style="width:200px"
					    ></el-date-picker>
					</el-form-item>
				</el-form>
				
				<el-form :model="form" class="margin-left" label-width="120px" v-if="ruleForm.type == 6">
					<el-form-item label="设备名称：">
						<template>
							<el-select
					            v-model="principalId"
								@change="choosePrincipal1"
								value-key="id"
								style="width:200px"
								placeholder="请选择"
							>
								<el-option
									v-for="item in shebeilist"
									:key="item.id"
									:label="item.name"
									:value="item"
								></el-option>
							</el-select>
						</template>
					</el-form-item>
					
				</el-form>
				<el-form :model="form" class="margin-left" label-width="120px" v-if="ruleForm.type == 7">
					<el-form-item label="设备名称：">
						<template>
							<el-select
					            v-model="principalId"
								@change="choosePrincipal1"
								value-key="id"
								style="width:200px"
								placeholder="请选择"
							>
								<el-option
									v-for="item in shebeilist"
									:key="item.id"
									:label="item.name"
									:value="item"
								></el-option>
							</el-select>
						</template>
					</el-form-item>
					
				</el-form>
			<!-- 	<div class="lu hnk"></div><div class="hnk jgxx">经纬度坐标</div>
				<div v-for="(item,index) in lnglat" :key="index" >
					<el-form ref="form" :model="form" class="margin-left">
						<el-row :gutter="20" style="margin-top:5px;">
							<el-col :span="10" >
								<el-form-item label="经度" style="width:40px;">
									<el-input class="handle-input" placeholder="" v-model="item.lng" style="width:150px;"></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="10" >
								<el-form-item label="纬度" style="width:40px;">
									<el-input class="handle-input" placeholder="" v-model="item.lat" style="width:150px;"></el-input>
								</el-form-item>
							</el-col>
						</el-row>
					</el-form>
				</div> -->
				<!-- <el-button type="success" @click="addListRow" style="margin:0 0 50px 20px;">新增坐标</el-button> -->
				<div class="footerFixed" style="margin-bottom:20px;box-shadow: 0 -1px 1px 1px #aaa;padding-left:20px;" >
					<el-button @click="cancelForm">取 消</el-button>
					<el-button type="primary" @click="$refs.drawer.closeDrawer()" :loading="loading">{{ loading ? '提交中 ...' : '确 定' }}</el-button>
				</div>
			</div>
        </el-drawer>
    </div>
</template>
 
<script>
	import { map_save,map_findByList } from "@/request/breedApi.js"
	import { user_findByAll } from '@/request/api';
	import BaiduMap from '../../../common/js'
    export default {
		inject: ['reload'], 
        data () { 
            return {
				shebeilist:[],
				principalId:'',
				peasantId:'',
				soilImg:'',
				opactity:0,
                name:'',
                area:'',
                lnglat:[{
                    lng:'',
                    lat:''
                }],
                addressname:'',
                color1: '#409EFF',
                polygonTool:'',
                zoom: '11',
                points: [],
                line: '',
                T: '',
                lay: '',
                map: '',
                drivingRoute: '',
                // _CarTrack: '',
                onDrawPolygon:"",
                config: '',
                iconMaker: [],
                dialog: false,
                loading: false,
				// 104.084439,30.631234
                latitude:30.631234,
                longtitude:104.084439,
                form:{},
                formLabelWidth: '80px',
                timer: null,
                list:'',
                urllist:"",
                dikuailists:'',
                localsearch:'',
                localSearchResult:'',
                geocoder:'',
                marker:'',
                zhongxin:'',
                lng:'',
                lat:'',
                polygon:'',
                polygonclick:'',
				markerTool:'',
				ruleForm:{
					type:'',
				},
				userList:[],
				mapList:[],
            }
        },
		created(){
			// if(location.href.indexOf('#reloaded')==-1){
			// 	location.href=location.href+"#reloaded";
			// }
		},
		mounted(){
		    // this.getshuju()
			setTimeout(this.getshuju(),1000)
			this.init()
			// setTimeout(this.dituMap(),1000)
		},
        methods:{
			gotrack(){
				this.$router.push({
					path:'/yzdigtalMap/trackmap',
				})
			},
			imgPreview(file,fileList){
			      this.soilImg =  URL.createObjectURL(file.raw);
			     let fileName = file.name;
			    let regex = /(.jpg|.gif|.png)$/;
			     if (regex.test(fileName.toLowerCase())) {
			         this.ruleForm.files = file.raw
			        this.ruleForm.soilImg = file.name
			    } else {
			         this.$message.error('请选择图片文件');
			     }
			},
			choosePrincipal(ele){
				this.ruleForm.peasantId = ele.id;
				this.ruleForm.peasantName = ele.name;
			},
			choosePrincipal1(ele){
				this.ruleForm.principalId = ele.id;
				this.ruleForm.principalName = ele.name;
			},
			init(){
				user_findByAll("").then((res) => {
					this.userList = res.data;
				});
			},
			formatTooltip(val) {
				return val / 100;
			 },
			 
			 farmarea(){
				 var obj = document.getElementById("three")
				 obj.style.color = "#409EFF"
				 
				 var obj = document.getElementById("one")
				 obj.style.color = "black"
			
				 var obj = document.getElementById("four")
				 obj.style.color = "black"
				 var obj = document.getElementById("five")
				 obj.style.color = "black"
				 var obj = document.getElementById("six")
				 obj.style.color = "black"
				 this.ruleForm.type = 2
				 var _this = this
				 // this.map.clearOverLays(); 
				 this.polygonTool.open();
				 this.markerTool.close()
				 this.polygonTool.addEventListener("draw",function huoqu(e){
				 	// console.log(e.currentArea/1000/1000*1500)
				 	var area = e.currentArea/1000/1000*1500
				 	_this.ruleForm.area = area.toFixed(2)
				     var list = e.currentLnglats
				     var s = JSON.stringify(list)
				     localStorage.setItem("list",s)
				     _this.lnglat = JSON.parse(s)
				     _this.dialog = true
				 }) 
				 
			 },
			// 气象传感
			weather(){
				var obj = document.getElementById("four")
				obj.style.color = "#409EFF"
				
				var obj = document.getElementById("one")
				obj.style.color = "black"
				var obj = document.getElementById("three")
				obj.style.color = "black"
				var obj = document.getElementById("five")
				obj.style.color = "black"
				var obj = document.getElementById("six")
				obj.style.color = "black"
				this.ruleForm.type = 6
				var _this = this
				this.markerTool.open()
				 this.polygonTool.close();
				this.markerTool.addEventListener("mouseup",function get(e){
					console.log(e.currentLnglats)
					_this.dialog = true
				})
			},
			//摄像头
			camera(){
				var obj = document.getElementById("five")
				obj.style.color = "#409EFF"
				var obj = document.getElementById("one")
				obj.style.color = "black"
				var obj = document.getElementById("three")
				obj.style.color = "black"
				var obj = document.getElementById("four")
				obj.style.color = "black"
				var obj = document.getElementById("six")
				obj.style.color = "black"
				this.ruleForm.type =7
				var _this = this
				this.markerTool.open()
				this.polygonTool.close();
				this.markerTool.addEventListener("mouseup",function get(e){
					_this.dialog = true
				})
			},
			// 全景图
			panoramagram(){
				var obj = document.getElementById("six")
				obj.style.color = "#409EFF"
				var obj = document.getElementById("one")
				obj.style.color = "black"
				var obj = document.getElementById("three")
				obj.style.color = "black"
				var obj = document.getElementById("four")
				obj.style.color = "black"
				var obj = document.getElementById("five")
				obj.style.color = "black"
				this.ruleForm.type=5
				var _this = this
				this.markerTool.open()
				this.polygonTool.close();
				this.markerTool.addEventListener("mouseup",function get(e){
					// console.log(e.currentLnglats)
					_this.dialog = true
				})
			},
			// 基地
            dialog111(){
				var obj = document.getElementById("one")
				obj.style.color = "#409EFF"
				var obj = document.getElementById("three")
				obj.style.color = "black"
				var obj = document.getElementById("four")
				obj.style.color = "black"
				var obj = document.getElementById("five")
				obj.style.color = "black"
				var obj = document.getElementById("six")
				obj.style.color = "black"
				this.ruleForm.type = 1
                var _this = this
                // this.map.clearOverLays(); 
                this.polygonTool.open();
				this.markerTool.close()
                this.polygonTool.addEventListener("draw",function huoqu(e){
					// console.log(e.currentArea/1000/1000*1500)
					var area = e.currentArea/1000/1000*1500
					_this.ruleForm.area = area.toFixed(2)
                    var list = e.currentLnglats
                    var s = JSON.stringify(list)
                    localStorage.setItem("list",s)
                    _this.lnglat = JSON.parse(s)
                    _this.dialog = true
                }) 
                
            },
            addListRow(){
                this.lnglat.push({
                    lng:'',
                    lat:''
                })
            },
            handleClose(done) {
                if (this.loading) {
                    return;
                }
                this.$confirm('确定要提交表单吗？')
                    .then(_ => {
                    this.loading = true;
					this.ruleForm.diaphaneity = this.ruleForm.diaphaneity/100
					this.ruleForm.coordinate = localStorage.getItem("list")
					console.log(this.ruleForm)
					map_save(this.ruleForm).then((res)=>{
						this.$notify({
						    title: '提示',
						    message: '保存成功',
						    type: 'success',
						    duration:1000
						});
						this.reload()
					})
                    this.timer = setTimeout(() => {
                        done();
                        // 动画关闭需要一定的时间
                        setTimeout(() => {
                        this.loading = false;
                        }, 400);
                    }, 2000);
                })
                .catch(_ => {});
            },
            cancelForm() {
				var obj = document.getElementById("one")
				obj.style.color = "black"
				var obj = document.getElementById("three")
				obj.style.color = "black"
				var obj = document.getElementById("four")
				obj.style.color = "black"
				var obj = document.getElementById("five")
				obj.style.color = "black"
				var obj = document.getElementById("six")
				obj.style.color = "black"
                this.loading = false;
                this.dialog = false;
                clearTimeout(this.timer);
            },
            getshuju(){
                map_findByList("").then((res)=>{
					this.mapList = res.data
					 var coorlist = JSON.parse(res.data[0].coordinate)
					 var arr=[]
					 
					 for(var j=0;j<coorlist.length;j++){
					     var s = coorlist[j]
					     arr.push(new T.LngLat(parseFloat(s.lng), parseFloat(s.lat)))
					 }
					 this.urllist = arr
					 if(this.mapList.length>0){
						 for (let i = 0; i < this.mapList.length; i++) {
							 var list = [];
							 var newList = [];
							 var list = this.mapList[i].coordinate.split(";");
							 // console.log(list)
							 for(var j = 0 ; j< list.length;j++){
								 newList = JSON.parse(list[j])
								 this.longtitude = parseFloat(newList[0].lng)
								 this.latitude = parseFloat(newList[0].lat)
							 }
						 }
					 }
					 
					 
					 BaiduMap.init()
					 	.then((T) => {  
					 	this.T = T
					 	this.zoom = 12
					 	// this.latitude = localStorage.getItem("latitude")
					 	this.map = new T.Map('mapDiv')// 初始化地图对象
					 	this.map.centerAndZoom(new T.LngLat(this.longtitude,this.latitude), 12)// 设置显示地图的中心点和级别
					 	//创建对象
					 		// var ctrl = new T.Control.MapType();
					 		//添加控件
					 		this.map.addControl(TMAP_HYBRID_MAP);
					 	// 创建图片对象
					 	var icon = new T.Icon({
					 		iconUrl: 'http://api.tianditu.gov.cn/img/map/markerA.png',
					 		iconSize: new T.Point(19, 27),
					 		iconAnchor: new T.Point(10, 25)
					 	})
					 	var config = {  
					 		strokeColor:"blue", //折线颜色  s
					 		fillColor:"blue",    //填充颜色。当参数为空时，折线覆盖物将没有填充效果  
					 		strokeWeight:"3px", //折线的宽度，以像素为单位  
					 		strokeOpacity:0.5,  //折线的透明度，取值范围0 - 1  
					 		fillOpacity:0.5, //填充的透明度，取值范围0 - 1  
					 		showLabel:true  //是否显示页面，默认为true
					 	}; 
					 	this.markerTool = new T.MarkTool(this.map,icon)
					 	this.polygonTool = new T.PolygonTool(this.map,config);  
					 	this.geocoder = new T.Geocoder(this.map)
					 	//注册测面工具绘制完成后的事件
					 	// type  undefined
					 	// console.log(this.mapList.length)
					 	for(var k=0;k<this.mapList.length;k++){
					 		// console.log(111)
					 		var con = JSON.parse(this.mapList[k].coordinate)
					 		
					 		this.polygon = new T.Polygon(con, { color: this.mapList[k].color,fillOpacity:this.mapList[k].diaphaneity })
					 		this.map.addOverLay(this.polygon)
					 	}
					 	// this.map.addOverLay(this.marker)
					 })
                })
            }, 
			
            handleAdd1() {
                var that = this
                this.modal1 = true
                this.formData1.type = '0'
                this.typeShow = true
                this.map.clearOverLays();  
                this.polygonTool.open(); 
                this.polygonTool.addEventListener("draw",function huoqu(e){
                    var list = e.currentLnglats
                    var s = JSON.stringify(list)
                    localStorage.setItem("list",s)
                    that.mas = JSON.parse(s) 
                })
                this.getmas()
            },
            sousuo(){
                this.geocoder.getPoint(this.addressname, function searchResult(result){
                    if(result.getStatus() == 0){
                        this.zhongxin = result.getLocationPoint()
                        this.marker = new T.Marker(result.getLocationPoint());
                        this.lnt = result.getLocationPoint().lng
                        this.lat = result.getLocationPoint().lat
                        localStorage.setItem("lng",result.getLocationPoint().lng)
                        localStorage.setItem("lat",result.getLocationPoint().lat)
                    }else{
                        alert(result.getMsg());
                    }
                })
				this.lng = localStorage.getItem("lng")
				this.lat = localStorage.getItem("lat")
				this.map.panTo(new T.LngLat(this.lng,this.lat), 18);
            }
        },
        
    }
</script>
 
<style scoped lang="less">
.el-scrollbar__wrap {
   overflow-x: hidden;
}
.mapDiv{
    width: 100%;
    height: 85vh;
    z-index:0;
}
.zoology{
    width:100px;
    text-align:center;
    height:60px;
	line-height:30px;
    position: absolute;
    top: 20px;
    left: 40px;
    z-index: 100;
    background:white;
    border-radius:6px;
}
.zoology1{
    width:200px;
    text-align:center;
    height:60px;
	line-height:30px;
    position: absolute;
    top: 20px;
    left: 150px;
    z-index: 100;
    background:white;
    border-radius:6px;
}
.zoology2{
    width:300px;
    text-align:center;
    height:60px;
	line-height:30px;
    position: absolute;
    top: 20px;
    left: 360px;
    z-index: 100;
    background:white;
    border-radius:6px;
}
.stbh{
    position:relative;
}
.margin-left{
    margin-left:20px;
}
.address{
    width:200px;
    text-align:center;
    height:60px;
    position: absolute;
    top: 20px;
    left: 670px;
    z-index: 100;
    background:white;
    border-radius:6px;
}
.addressinput{
    width:150px;
    height:57px;
}
.addressspan{
    font-size:14px;
}
.lu{
    width: 8px;
    height: 16px;
    background: greenyellow;
    margin-left:10px;
}
.hnk{
    display:inline-block;
}
.jgxx{
    margin-left:10px ;
    font-weight:600;
    font-size: 15px;
}
/* .el-drawer.rtl{
    overflow: scroll;
} */
// .demo-drawer__content{
// 	display: flex;
// 	flex-direction: column;
// 	padding:20px;
// 	height:100%;
// 	.el-form{
// 		flex:1;
// 		height:0;
// 		overflow: auto;
// 	}
// 	.drawer-footer{
// 		display:flex;
// 		.el-button{
// 			flex:1;
// 		}
// 	}
// }
.el-drawer__body{
	// height:0;
	overflow: auto;
}
	.avatar-uploader .el-upload {
	    border: 1px dashed #d9d9d9;
	    border-radius: 6px;
	    cursor: pointer;
	    position: relative;
	    width:180px;
	    overflow: hidden;
	  }
	  
	  .avatar-uploader .el-upload:hover {
	    border-color: #409EFF;
	  }
	  .el-upload--text{
	      width:180px;
	  }
	  .avatar-uploader-icon {
	    font-size: 28px;
	    color: #8c939d;
	    width: 178px;
	    height: 178px;
	    line-height: 178px;
	    text-align: center;
	  }
	  .avatar {
	    width: 178px;
	    height: 178px;
	    display: block;
	  }
</style>